<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH.'libraries/openid.php';

class Userland {
	public function authenticate($login, $pass, $no_hash = false, $full_user = false)
	{
		$CI =& get_instance();
		$CI->load->database();
		
		// load the user record (plus we need to get the salt)
		$user_select = $full_user ? "*" : "id,login,crypted_password,salt";
		$user_query  = $CI->db->query("select {$user_select} from users where login = ? limit 1", array($login));
		if ($user_query->num_rows() == 1)
		{
			$user 	  = $user_query->first_row();
			$enc_pass = $no_hash ? $pass : $this->encrypt_pass($pass, $user->salt);
			
			// Log the auth call
			log_message('debug', 'AUTH ' . $user->login);
			//die('auth' . '---' . $user->login . '---' . $user->crypted_password . '---' . $enc_pass);
			
			if ($user->crypted_password == $enc_pass)
			{
				return $full_user ? $user : true;
			}
		}
	}
	
	public function encrypt_pass($pass, $salt)
	{
		return sha1("--{$salt}--{$pass}--");
	}
	
	public function is_following($user_id)
	{
		if (!$this->logged_in())
			return false;
			
		$CI =& get_instance();
		$CI->load->database();
		$params = array($this->current_user()->id, $user_id);
		$query  = $CI->db->query("SELECT * FROM followers WHERE user_id = ? AND followed_user_id = ? LIMIT 1",
			$params);
		return $query->num_rows() ? true : false;
	}
	
	public function save_user_cookie($login, $pass, $override_domain = false, $no_encrypt = false)
	{
		global $BBX;
		
		$CI =& get_instance();
		$CI->load->database();
		
		$salt	  = $CI->db->query('select salt from users where login = ?', array($login))->first_row()->salt;
		$enc_pass = $no_encrypt ? $pass : $this->encrypt_pass($pass, $salt);
		if (!get_cookie('bricabox_login'))
		{
			$data = array(
				'name' 		=> 'bricabox_login',
				'value' 	=> "{$login}|{$enc_pass}",
				'expire' 	=> 604800, // 7 days
				'domain'	=> ($override_domain ? $override_domain : $this->_cookie_domain())
			);
			set_cookie($data);
		}
		return $enc_pass;
	}
	
	public function store_location()
	{
		global $BBX;
		
		$CI =& get_instance();
		$CI->load->model('Redirect_model');
		
		$value = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $BBX['request']['host'];
		$value = prep_url($value);
		
		return $CI->Redirect_model->store_redirect($value);
	}
	
	public function redirect_back($token, $login, $pass)
	{
		$CI =& get_instance();
		$CI->load->model('Redirect_model');
		$CI->Redirect_model->redirect_to($token, false, $login, $pass);
	}
	
	// returns a query result for the currently logged-in user, or false if no user is logged in
	// does some simple caching (memory-based) too
	public function current_user($clear_cache = false)
	{
		global $BBX;
		
		if (isset($BBX['current_user']))
			return $BBX['current_user'];
			
		if ($clear_cache)
			unset($BBX['current_user']);
			
		$ret = false;
		$c	 = get_cookie('bricabox_login');
		if ($c)
		{
			list($login, $pass) = explode('|', $c);
			
			// authenticate first
			$user = $this->authenticate($login, $pass, true, true); // don't re-hash the password
			if ($user)
			{
				log_message('debug', "in current_user() and authenticated okay: {$user->login}");
				$BBX['current_user'] = $user;
				$ret 				 = $user;
			}
		}
		return $ret;
	}
	
	// returns false or the role_id for the current user in the context of the current bricabox
	public function user_role()
	{
		global $BBX;
		
		if (!isset($BBX['bricabox']) || !$this->logged_in())
			return false;
			
		if ($this->current_user()->is_admin)
		{
			return 5;
		}
		
		return $this->get_role_id($BBX['bricabox']->id, $this->current_user()->id);
	}
	
	public function get_role_id($bricabox_id, $user_id)
	{
		$CI =& get_instance();	
		$CI->load->database();
			
		$params = array($bricabox_id, $user_id);
		$query  = $CI->db->query('select roles.id as role_id from roles
				where roles.id =
					(select memberships.role_id from memberships
						where memberships.bricabox_id = ?
							and memberships.user_id = ? limit 1) limit 1', $params);
		if ($query->num_rows() == 1)
		{
			$_role_id = $query->first_row()->role_id;
			log_message('debug', 'user role: '.$_role_id);
			return $_role_id;
		}
	}
	
	public function logged_in()
	{
		if ($this->current_user())
			return true;
	}
	
	public function is_admin()
	{
		if ($this->logged_in() && $this->current_user()->is_admin)
			return true;
	}
	
	public function logout($redirect = true)
	{
		delete_cookie('bricabox_login', $this->_cookie_domain());
		delete_cookie('bricabox_redirect', $this->_cookie_domain());
		
		unset($_COOKIE['bricabox_login']);
		unset($_COOKIE['bricabox_redirect']);
		
		if ($redirect)
			header('Location: /');
	}
	
	public function find_user_by_openid($identity_url)
	{
		$CI =& get_instance();
		$CI->load->database();
		
		$query = $CI->db->query('select * from users where identity_url = ? limit 1', array($identity_url));
		if ($query->num_rows() == 1)
			return $query->first_row();
	}
	
	public function create_user_from_openid($identity_url, $sreg = array())
	{
		$_user = $this->find_user_by_openid($identity_url);
		if ($_user)
			return $_user;
		
		$CI =& get_instance();
		$CI->load->database();
		
		$pass_str 	= sha1("{$identity_url}--kicks--ass--03291986");
		$salt 		= sha1(time().$identity_url."--openid--rules");
		$pass 		= $this->encrypt_pass($pass_str, $salt);
		
		$params = array(
			url_title($identity_url),
			(isset($sreg['email']) ? $sreg['email'] : ''),
			$pass,
			$salt,
			$identity_url,
			(isset($sreg['nickname']) ? $sreg['nickname'] : 'NULL'),
			url_title($identity_url)
		);
		$query = $CI->db->query('insert into users (login,email,crypted_password,salt,created_at,updated_at,identity_url,display_name,url_alias)
			values(?,?,?,?,NOW(),NOW(),?,?,?)', $params);

		// send signup email if $sreg['email'] not "" or NULL
		// TODO

		return $this->find_user_by_openid($identity_url);
	}
	
	public function add_to_cm($login, $email, $add = true) // if false, remove
	{
		try {


			// Make the call
			$cm = new CampaignMonitor(CAMPAIGN_MONITOR_API_KEY);
			if ($add)
			{
				$cm_ret = $cm->subscriberAddAndResubscribe($email, $login, CAMPAIGN_MONITOR_MASTERLIST_ID);
			}
			else
			{
				$cm_ret = $cm->subscriberUnsubscribe($email, CAMPAIGN_MONITOR_MASTERLIST_ID);
			}
			return true;

		} catch (SoapFault $exception) {
		}
	}
	
	/* private methods */
	private function _cookie_domain()
	{
		global $BBX;
		return ".{$BBX['request']['subless_portless_host']}";
	}
	
	/* deprecated methods */
	public function deprecated_store_location()
	{
		global $BBX;
		$value = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/';
		$data  = array(
			'name' 		=> 'bricabox_redirect',
			'value' 	=> $value,
			'expire' 	=> 0,
			'domain'	=> $this->_cookie_domain()
		);
		set_cookie($data);
	}
	
	public function deprecated_redirect_back($default = '/')
	{
		$to = get_cookie('bricabox_redirect');
		if ($to)
		{
			delete_cookie('bricabox_redirect');
			$_to = $to;
		}
		else
		{
			$_to = $default ? $default : '/';
		}
		header("Location: $_to");
	}
	
	// deprecated but reqiured for now
	public function redirect_if_logged_in()
	{
	}
}
?>